package com.woniu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.entity.PageResult;
import com.woniu.mapper.*;
import com.woniu.pojo.Car;
import com.woniu.pojo.Order;
import com.woniu.pojo.User;
import com.woniu.service.ICarService;
import com.woniu.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Energy
 * @since 2022-10-12
 */
@Service
public class CarServiceImpl extends ServiceImpl<CarMapper, Car> implements ICarService {


    @Resource
    private OrderMapper orderMapper;

    @Resource
    private CarMapper carMapper;
    @Resource
    private UserMapper userMapper;

    @Resource
    private PatrolMapper patrolMapper;

    @Resource
    private SpaceMapper spaceMapper;

    @Override
    public List<CarWithOrderListVo> queryWithOrderListByUserId(Long userId) {
        // 先正常的查询车辆数据
        QueryWrapper<Car> carWrapper = new QueryWrapper<>();
        carWrapper.eq("user_id", userId);
        List<Car> carList = carMapper.selectList(carWrapper);

        // 查询订单数据并保存到车辆数据里
        List<CarWithOrderListVo> voList = new ArrayList<>();
        for (Car car : carList) {
            CarWithOrderListVo carVo = new CarWithOrderListVo();
            BeanUtils.copyProperties(car, carVo);

            QueryWrapper<Order> orderWrapper = new QueryWrapper<>();
            orderWrapper.eq("car_id", car.getId());
            List<Order> orderList = orderMapper.selectList(orderWrapper);
            carVo.setOrderList(orderList);

            voList.add(carVo);
        }
        return voList;
    }

    /**
     * 根据用户信息分页查询其对应的车辆信息和订单信息
     * @param carQueryVo 用户查询条件信息
     * @param currentPage 当前页
     * @param pageSize 每页最大记录数
     * @return
     */
    public PageResult search(CarQueryVo carQueryVo, Integer currentPage, Integer pageSize) {

        List<CarVo> carVoList=new ArrayList<>();
        if(StringUtils.isEmpty(carQueryVo.getStatus())&&StringUtils.isEmpty(carQueryVo.getWechat())&&StringUtils.isEmpty(carQueryVo.getNickname())&&StringUtils.isEmpty(carQueryVo.getPhone())){

            IPage<Car> carIPage=new Page<>(currentPage,pageSize);
            IPage<Car> carIPage1 = carMapper.selectPage(carIPage, null);
            for (Car car : carIPage1.getRecords()) {
                CarVo carVo = new CarVo();

                carVo.setCarId(car.getId());
                carVo.setStatus(car.getStatus());
                carVo.setUserId(car.getUserId());
                carVo.setType(car.getType());
                carVo.setNum(car.getNum());
                carVo.setCreateTime(car.getCreateTime());

                Long userId = car.getUserId();

                if(userId!=0){
                    carVo.setNickname(userMapper.selectById(userId).getNickname());
                }

                QueryWrapper<Order> orderQueryWrapper=new QueryWrapper<>();
                if(orderQueryWrapper.eq("car_id",car.getId())!=null){
                    orderQueryWrapper.eq("car_id",car.getId());
                }
                List<Order> orders = orderMapper.selectList(orderQueryWrapper);

                carVo.setOrderNum(orders.size());

                //设置未交费订单数量
                BigDecimal noPayOrderNum=new BigDecimal(0);
                //消费金额
                BigDecimal consumeMoney = new BigDecimal(0);
                //未交费订单金额
                BigDecimal noPayOrderMoney=new BigDecimal(0);


                for (int i = 0; i < orders.size(); i++) {
                    //这是未交费订单
                    if(orders.get(i).getStatus().equals("1")){
                        //未缴费订单数量
                        noPayOrderNum=noPayOrderNum.add(new BigDecimal(1));
                        //未缴费订单金额
                        BigDecimal money3 = orders.get(i).getMoney();
                        if(money3!=null){
                            noPayOrderMoney=noPayOrderMoney.add(money3);
                        }

                    }
                    //消费金额
                    BigDecimal money = orders.get(i).getMoney();
                    if(money!=null){
                        consumeMoney=consumeMoney.add(money);
                    }
                }
                carVo.setNoPayOrderNum(noPayOrderNum);
                carVo.setConsumeMoney(consumeMoney);
                carVo.setNoPayOrderMoney(noPayOrderMoney);
                carVoList.add(carVo);
            }
            PageResult pageResult=new PageResult(carIPage1.getTotal(),carVoList);
            return pageResult;
        }

        Page<Car> page=new Page<>(currentPage,pageSize);

        IPage<Car> carIPage = carMapper.selectPages(page,carQueryVo);
        for (Car car : carIPage.getRecords()) {
            CarVo carVo=new CarVo();
            if(car.getUserId()!=null){
                carVo.setNickname(userMapper.selectById(car.getUserId()).getNickname());      //车辆所属用户昵称
            }
            carVo.setUserId(car.getUserId());                    //车辆所属用户id
            carVo.setCarId(car.getId());                //车辆id
            carVo.setNum(car.getNum());                 //车牌号
            carVo.setType(car.getType());               //车牌类型
            carVo.setCreateTime(car.getCreateTime());   //创建时间
            carVo.setStatus(car.getStatus());           //车辆状态



            Long carId = car.getId();
            QueryWrapper<Order> orderQueryWrapper=new QueryWrapper<>();
            QueryWrapper<Order> car_id = orderQueryWrapper.eq("car_id", carId);
            List<Order> orderList = orderMapper.selectList(car_id);

            //订单数量
            int orderSize = orderList.size();
            carVo.setOrderNum(orderSize);
            //设置未交费订单数量
            BigDecimal noPayOrderNum=new BigDecimal(0);
            //消费金额
            BigDecimal consumeMoney = new BigDecimal(0);
            //未交费订单
            BigDecimal noPayOrderMoney=new BigDecimal(0);

            for (int i = 0; i < orderList.size(); i++) {
                //这是未交费订单
                if(orderList.get(i).getStatus().equals("1")){
                    //未缴费订单数量
                    noPayOrderNum=noPayOrderNum.add(new BigDecimal(1));
                    //未缴费订单金额
                    BigDecimal money3 = orderList.get(i).getMoney();
                    if(money3!=null){
                        noPayOrderMoney=noPayOrderMoney.add(money3);
                    }

                }
                //消费金额
                BigDecimal money = orderList.get(i).getMoney();
                if(money!=null){
                    consumeMoney=consumeMoney.add(money);
                }
            }
            carVo.setNoPayOrderNum(noPayOrderNum);
            carVo.setConsumeMoney(consumeMoney);
            carVo.setNoPayOrderMoney(noPayOrderMoney);

            carVoList.add(carVo);
        }
        PageResult pageResult=new PageResult(carIPage.getTotal(),carVoList);

        return pageResult;

    }

    /**
     * 车辆订单信息表的数据查询
     * @param carId 车辆id
     * @return
     */
    public PageResult carOrderSearch(Long carId) {
        //根据车辆id查询其对应的车牌号
        String num = carMapper.selectById(carId).getNum();
        //1.构建车辆订单查询条件
        QueryWrapper<Order> orderQueryWrapper=new QueryWrapper<>();
        if(carId!=null){
            orderQueryWrapper.eq("car_id",carId);
        }
        //构建分页对象
        IPage<Order> page=new Page<>(1,10);
        //调用方法查询车辆订单数据
        IPage<Order> orderIPage = orderMapper.selectPage(page, orderQueryWrapper);
        List<CarOrderVo> carOrderVoList=new ArrayList<>();
        for (Order order : orderIPage.getRecords()) {
            CarOrderVo carOrderVo=new CarOrderVo();
            //设置订单编号
            carOrderVo.setOrderId(order.getId());
            //设置车牌号
            carOrderVo.setCarNum(num);
            //设置订单支付方式
            carOrderVo.setPayWay(order.getPayWay());
            //设置订单状态
            carOrderVo.setStatus(order.getStatus());
            //设置订单提交时间
            carOrderVo.setCreateTime(order.getCreateTime());
            //设置订单金额
            carOrderVo.setMoney(order.getMoney());

            carOrderVoList.add(carOrderVo);

        }
        PageResult pageResult=
                new PageResult(orderIPage.getTotal(),carOrderVoList);

        return pageResult;
    }

    /**
     * 车辆订单条件查询，根据订单条件查询车辆订单信息
     * @param currentPage 当前页
     * @param pageSize 每页最大记录数
     * @param carId 车辆id
     * @param carOrderQueryVo  车辆订单查询条件
     * @return
     */
    public PageResult carOrderPageSearch(Integer currentPage, Integer pageSize, Long carId, CarOrderQueryVo carOrderQueryVo) {
        //1.构建查询条件,查询出所有符合条件的订单
        QueryWrapper<Order> queryWrapper=new QueryWrapper<>();
        if(carId!=null){
            queryWrapper.eq("car_id",carId);
        }
        if(carOrderQueryVo!=null){
            if(!StringUtils.isEmpty(carOrderQueryVo.getOrderNum())){
                queryWrapper.like("id",carOrderQueryVo.getOrderNum());
            }
            if(carOrderQueryVo.getCreateTime()!=null){
                queryWrapper.eq("create_time",carOrderQueryVo.getCreateTime());
            }
            if(!StringUtils.isEmpty(carOrderQueryVo.getPayWay())){
                queryWrapper.eq("pay_way",carOrderQueryVo.getPayWay());
            }
            if(!StringUtils.isEmpty(carOrderQueryVo.getStatus())){
                queryWrapper.eq("status",carOrderQueryVo.getStatus());
            }
        }
        //构建分页对象
        IPage<Order> page=new Page<>(currentPage,pageSize);
        IPage<Order> orderIPage = orderMapper.selectPage(page, queryWrapper);

        //根据车辆id查询其对应的车牌号
        String num = carMapper.selectById(carId).getNum();

        List<CarOrderVo> carOrderVoList=new ArrayList<>();
        for (Order order : orderIPage.getRecords()) {

            CarOrderVo carOrderVo=new CarOrderVo();

            //设置订单编号
            carOrderVo.setOrderId(order.getId());
            //设置车牌号
            carOrderVo.setCarNum(num);
            //设置订单支付方式
            carOrderVo.setPayWay(order.getPayWay());
            //设置订单状态
            carOrderVo.setStatus(order.getStatus());
            //设置订单提交时间
            carOrderVo.setCreateTime(order.getCreateTime());
            //设置订单金额
            carOrderVo.setMoney(order.getMoney());

            carOrderVoList.add(carOrderVo);

        }
        PageResult pageResult=
                new PageResult(orderIPage.getTotal(),carOrderVoList);

        return pageResult;

    }

    /**
     * 修改车辆状态
     * @param carId 车辆id
     * @return flag
     */
    public Boolean modifyCarStatus(String carId) {
        Date date=new Date();
        Boolean flag=carMapper.updateCarStatus(carId,date);
        return flag;
    }

    /**
     * 修改车辆状态正常
     * @param carId
     * @return
     */
    public Boolean modifyCarStatusNormal(String carId) {
        Date date=new Date();
        Boolean flag=carMapper.updateCarStatusNormal(carId,date);
        return flag;
    }

    /**
     * 将车辆与用户进行解绑
     * @param carId
     * @return
     */
    public Boolean unbindingUserAndCar(String carId) {
        Date date=new Date();
        Boolean flag=carMapper.updateCarUser(carId,date);
        return flag;
    }
    @Override
    public Boolean bingdingUserAndCar(String carId, String userId) {
        Long id = carMapper.selectById(carId).getUserId();
        //判断车辆是否已经进行过绑定了，如果已绑定，则需先解除之前绑定的用户才能绑定新的用户
        if(id!=null){
            return false;
        }
        Date date=new Date();
        Boolean flag=carMapper.updateCarOfUser(carId,userId,date);
        return flag;
    }

    /**
     * 根据订单id查询车辆订单详细信息
     * @param orderId
     * @return
     */
    public CarOrderDetailVo carOrder(Long orderId) {
        Order order = orderMapper.selectById(orderId);
        CarOrderDetailVo carOrderDetailVo=new CarOrderDetailVo();
        carOrderDetailVo.setOrderId(orderId);                             //订单编号
        carOrderDetailVo.setCarId(order.getCarId());                      //车辆id
        String num = carMapper.selectById(order.getCarId()).getNum();
        carOrderDetailVo.setCarNum(num);                                  //车牌号码
        carOrderDetailVo.setCreateTime(order.getCreateTime());            //驶入时间
        carOrderDetailVo.setLeaveTime(order.getLeaveTime());              //驶离时间
        carOrderDetailVo.setOrderMoney(order.getMoney());                 //订单金额
        carOrderDetailVo.setPayMoney(order.getPayMoney());                //支付金额
        carOrderDetailVo.setPayTime(order.getPayTime());                  //支付时间
        carOrderDetailVo.setStatus(order.getStatus());                    //订单状态
        carOrderDetailVo.setPayWay(order.getPayWay());                    //支付方式
        String patrolName = patrolMapper.selectById(order.getPatrolId()).getName();
        carOrderDetailVo.setPatrolName(patrolName);                       //巡检员姓名
        String spaceName = spaceMapper.selectById(order.getSpaceId()).getName();
        carOrderDetailVo.setSpaceName(spaceName);                         //泊位名称
        return carOrderDetailVo;
    }


}
